
const app = getApp()
const db = wx.cloud.database()
const $ = db.command.aggregate
const to = app.require("lib/awaitTo")
const { listData, loadData } = app.require("lib/loadList")
const { getUser } = app.require("utils/request/user")
// 引入mixins
const follow = require("./mixins/follow")
Page({
	mixins: [follow],
	data: {
		userId: "",
		user: {},
		me: wx.getStorageSync('user'),
		searchText: "",
		post: listData
	},
	onLoad(e) {
		this.setData({
			userId: e.userId
		})
		this.getUser()
		this.getPost()
		this.getFollow()
	},
	async getUser() {
		// 获取用户信息
		const [err, res] = await to(getUser(this.data.userId), "getUser")
		if (err) {
			wx.navigateBack()
			return
		}
		const user = res[0].data
		user.postNum = res[1].total
		user.favorNum = res[2].list.length ? res[2].list[0].favorNum : 0
		this.setData({
			user
		})

	},
	async getPost(loadType = "getData") {
		// 获取用户发布文章
		const reg = new RegExp(`${this.data.searchText}`, "i")
		const [err, res] = await to(db.collection("post").aggregate()
			.match({
				"title": reg
			})
			.limit(10)
			.sort({
				createTime: -1
			})
			.end(), "getPost")
		loadData.call(this, {
			resData: res.list,
			targetObj: "post",
			loadType
		})
	},
	showPost(e) {
		// 跳转至用户发布的文章
		const post = e.currentTarget.dataset.post
		const { showPostDetail } = app.require("utils/router/post")
		showPostDetail(post._id, post.userId)
	},
	changeContent(e) {
		// 输入框输入内容
		this.setData({ "searchText": e.detail })
	},
	clearContent() {
		// 清空输入输入框内容
		this.setData({ "searchText": "" })
		this.getPost()
	},
	onReachBottom() {
		// 触底加载
		if (this.data.post.nomore) return
		this.getPost()
	}

})